package com.niubility.shiro.realms;

import com.niubility.entity.Users;
import com.niubility.server.IPwdService;
import com.niubility.server.IUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;

@Controller
public class SecondRealm extends AuthenticatingRealm {
    @Resource
    private IUserService usersService;
    @Resource
    private IPwdService pwdService ;

    @Override
    public String getName() {
        return "SecondRealm";

    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //1.把AuthenticationToken转化成UsernamePasswordToken
        UsernamePasswordToken uptoken = (UsernamePasswordToken)token;
        //2.从UsernamePasswordToken 中获取userName,userPhone
        String userTel=uptoken.getUsername();
        String userPwd=uptoken.getPassword().toString();
        Users user=this.usersService.selectUserByTel(userTel);
        int userId= 0;
        try{
            userId = user.getUserId();
        }catch (Exception e){
            //System.out.println("社团是用的是jdbcRealm");
        }

        //通过userid找密码
        ////System.out.println(this.pwdService.LoadById(userId));

        //获取到的是加盐之后的值
        String userPassword=this.pwdService.CipherEncryptionBySHA1(userPwd,userTel);
        //3.调用数据库的方法，从数据库中 查询userName 对应的用户记录
        ////System.out.println("从数据库中获取"+userTel+"所对应 的用户信息。");
        if(user==null){
            throw new UnknownAccountException("用户不存在!");
        }

        //以下信息是从数据库中获取的
        //principal ：认证的实体信息	  可以是userName也可以是数据表对应的用户的实体类对象
        Object principal = user;
        Object credentials = pwdService.LoadById(userId).getUserPwd();
        String realmName = getName();
        //realmName:当前对象的name调用父类的getName方法
        //盐值：
        ByteSource credentialsSalt=ByteSource.Util.bytes(userTel);
        //SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(principal, credentials, realmName);
        SimpleAuthenticationInfo info=null;
        info=new SimpleAuthenticationInfo(principal,credentials,credentialsSalt,realmName );
        return info;
    }
}
